package com.gdut.huayan.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gdut.huayan.constant.SecurityConstant;
//import com.gdut.huayan.constant.WechatConstant;
import com.gdut.huayan.constant.WechatConstant;
import com.gdut.huayan.dao.RoleMapper;
import com.gdut.huayan.dao.UserMapper;
import com.gdut.huayan.dao.UserRoleMapper;
import com.gdut.huayan.entity.dto.PageQuery;
import com.gdut.huayan.entity.po.Role;
import com.gdut.huayan.entity.po.User;
import com.gdut.huayan.entity.po.UserRole;
import com.gdut.huayan.entity.vo.UserLogin;
import com.gdut.huayan.service.FileService;
import com.gdut.huayan.service.UserService;
import com.gdut.huayan.service.exception.BaseException;
import com.gdut.huayan.utils.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private WebJsonUtils webJsonUtils;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private FileService fileService;


    @Override
    public PageInfo<User> getUserList(PageQuery pageQuery) {
        PageHelper.startPage(pageQuery.getPage(), pageQuery.getSize());
        PageInfo<User> users = new PageInfo<>(baseMapper.queryUserList(pageQuery));
        /*users.getList().forEach(t -> t.setAvatarFileId(AliyunUtils.getDownloadLink(t.getAvatarUrl(), new Date().getTime() + SecurityConstant.TIME_ONE_DAY)));*/
        return users;
    }

    @Override
    @Transactional
    public UserLogin userLogin(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + WechatConstant.APP_ID + "&secret=" + WechatConstant.APP_SECRET +
                "&js_code=" + code + "&grant_type=authorization_code";
        JSONObject jsonObject = webJsonUtils.sendGet(url);
        if (jsonObject.containsKey("errcode")) {
            throw new BaseException(401, "微信服务器拒绝您登录，可能由于您频繁尝试或是被风控系统拦截");
        }
        String openId = jsonObject.getString("openid");
        String unionId = jsonObject.getString("unionid");
        Wrapper<User> wrapper = new QueryWrapper<User>().eq("open_id", openId);
        User user = getOne(wrapper);
        UserLogin userLogin = new UserLogin();
        if (user == null) {
            User insertUser = new User();
            insertUser.setStatus(0);
            insertUser.setUnionId(unionId);
            insertUser.setOpenId(openId);
            insertUser.setRegisterTime(LocalDateTime.now());
            save(insertUser);
            userRoleMapper.insert(new UserRole(null, insertUser.getId(), 1L));
            user = insertUser;
        }
        userLogin.setUserProfile(user);
        long expire = new Date().getTime() + SecurityConstant.TIME_ONE_DAY;
        String authToken = WebJwtUtils.generate(
                user.getId().toString(),
                SecurityConstant.TOKEN_SECRET,
                expire
        );
        List<Role> userRole = roleMapper.getUserRole(user.getId());
        Map<String, String> cacheMap = new HashMap<>();
        cacheMap.put(SecurityConstant.TOKEN_PREFIX, authToken);
        StringBuilder userRoleString = new StringBuilder();
        for (int i = 0; i < userRole.size(); i++) {
            Role role = userRole.get(i);
            if(role.getId() == 2){
                userLogin.setAdmin(true);
            }
            if (i == 0) {
                userRoleString.append(role.getSign());
            }
            userRoleString.append("&").append(role.getSign());
        }
        cacheMap.put(SecurityConstant.ROLE_PREFIX, userRoleString.toString());
        redisUtils.putHash(SecurityConstant.USER_PREFIX + user.getId(), cacheMap, SecurityConstant.TIME_ONE_DAY);
        userLogin.setExpireTime(expire);
        userLogin.setAccessToken(authToken);
        return userLogin;
    }

    @Override
    public String getUUID() {
        String uuid = UUID.randomUUID() + "-" + new Date().getTime();
        redisUtils.put(SecurityConstant.SCAN_PREFIX + uuid, "WAIT", SecurityConstant.TIME_TWENTY_MINUTES);
        return uuid;
    }

    @Override
    public String getStatus(String uuid) {
        String s = redisUtils.get(SecurityConstant.SCAN_PREFIX + uuid);
        if (s == null) {
            throw new BaseException(401, "不存在此登录账号！");
        }
        return s;
    }

    @Override
    public void confirmLogin(String uuid, String token) {
        redisUtils.put(SecurityConstant.SCAN_PREFIX + uuid, token, SecurityConstant.TIME_TWENTY_MINUTES);
    }

    @Override
    public User getUserMessage() {
        return super.getById(SecurityUtils.getUserIdNumber());
        /*
        user.setAvatarFileId(AliyunUtils.getDownloadLink(user.getAvatarUrl(), new Date().getTime() + SecurityConstant.TIME_ONE_DAY));
        */
    }

    @Override
    public Map<String, String> getUploadLink() {
        Map<String, String> result = new HashMap<>();
        long now = new Date().getTime();
        String filePath = "avatar/" + SecurityUtils.getUserIdNumber() + UUID.randomUUID() + now + ".jpeg";
        String uploadLink = AliyunUtils.getUploadLink(filePath, "image/jpeg", now + SecurityConstant.TIME_TEN_MINUTES);
        result.put("filePath", filePath);
        result.put("uploadLink", uploadLink);
        return result;
    }

    @Override
    public boolean updateById(User user) {
        user.setId(SecurityUtils.getUserIdNumber());
        user.setOpenId(null);
        user.setUnionId(null);
        user.setRegisterTime(null);
        user.setStatus(null);

        if (user.getPhoneNumber() != null) {
            String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + WechatConstant.ACCESS_TOKEN;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", user.getPhoneNumber());
            JSONObject returnObject = webJsonUtils.sendPost(url, jsonObject);
            user.setPhoneNumber(returnObject.getJSONObject("phone_info").getString("phoneNumber"));
        }
        System.out.println("fileId:"+user.getAvatarFileId());
        return super.updateById(user);
    }

    @Override
    public boolean updateByAdmin(User user) {
        user.setOpenId(null);
        user.setUnionId(null);
        user.setRegisterTime(null);

        if (user.getPhoneNumber() != null) {
            String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + WechatConstant.ACCESS_TOKEN;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", user.getPhoneNumber());
            JSONObject returnObject = webJsonUtils.sendPost(url, jsonObject);
            user.setPhoneNumber(returnObject.getJSONObject("phone_info").getString("phoneNumber"));
        }
        return super.updateById(user);
    }

}
